<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>优化版树形菜单 - 文件夹图标与顶部操作</title>
    <style>
        
        .container {
            width: 100%;
            max-width:380px;
            display: flex;
            flex-wrap: wrap;
        }
        
        .card {
            flex: 1;
            transition: transform 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
       
        .toolbar {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .toolbar-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            background: #4e54c8;
            color: white;
            border: none;
            border-radius: 10px;
            padding: 10px 20px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
            box-shadow: 0 4px 10px rgba(78, 84, 200, 0.3);
        }
        
        .toolbar-btn:hover {
            background: #3f43a8;
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(78, 84, 200, 0.4);
        }
        
        .toolbar-btn:disabled {
            background: #adb5bd;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .tree-container {
            overflow: hidden;
            height: 500px;
            overflow-y: auto;
        }
        
        .tree-menu {
            list-style: none;
            padding-left: 0;
        }
        
        .tree-node {
            margin: 8px 0;
            position: relative;
            transition: all 0.2s;
			list-style-type: none; /* 去掉小黑点 */
			padding-left: 0; /* 通常也会将左侧的内边距设置为0，移除默认的缩进 */
        }
        
        .node-content {
            display: flex;
            align-items: center;
            padding: 8px 8px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            background: #f8f9fa;
            position: relative;
            z-index: 2;
            border: 1px solid #e9ecef;
        }
        
        .node-content:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }
        
        .node-content.selected {
            background: #4e54c8;
            color: white;
            box-shadow: 0 4px 12px rgba(78, 84, 200, 0.3);
            border-color: #4e54c8;
            transform: translateX(8px);
        }
        
        .node-content.selected .toggle-icon {
            color: white;
        }
        
        .toggle-icon {
            width: 20px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: #4e54c8;
            transition: transform 0.2s;
			
        }
        
        .folder-icon {
            color: #ff9800;
            width: 20px;
            text-align: center;
        }
        
        .node-label {
            flex: 1;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
			padding-top:2px;
			padding-left:2px;
        }
        
        .children {
            padding-left: 15px;
            border-left: 1px dashed #adb5bd;
            margin-left: 15px;
            display: none;
        }
        
        .expanded > .children {
            display: block;
        }
        
        .loading {
            color: #6c757d;
            font-size: 14px;
            padding: 10px 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .spinner {
            border: 2px solid rgba(0, 0, 0, 0.1);
            border-left-color: #4e54c8;
            border-radius: 50%;
            width: 16px;
            height: 16px;
            animation: spin 1s linear infinite;
        }
        
      
          /* 自定义SVG图标 */
        .svg-icon {
            display: inline-block;
            width: 1em;
            height: 1em;
            fill: currentColor;
            vertical-align: middle;
        }
   	@font-face {
	  	font-family: 'iconfont';
	  	src: url('font_folder/iconfont.ttf?t=1752029364521') format('truetype');
		}
		.iconfont-folder {
  			font-family: "iconfont" !important;
 			 font-size: 16px;
  			font-style: normal;
  			-webkit-font-smoothing: antialiased;
 			 -moz-osx-font-smoothing: grayscale;
		}
		.iconfont-arrow {
  			font-family: "iconfont" !important;
 			 font-size: 20px;
  			font-style: normal;
  			-webkit-font-smoothing: antialiased;
 			 -moz-osx-font-smoothing: grayscale;
		}
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
          
            <!-- 顶部操作栏 -->
            <div class="toolbar">
                <button id="addRootBtn" class="toolbar-btn">
                    <svg class="svg-icon" viewBox="0 0 24 24" style="width:20px;height:20px;">
                        <path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" />
                    </svg> 添加根节点
                </button>
                <button id="addChildBtn" class="toolbar-btn" disabled>
                    <i class="iconfont-folder">&#xe730;</i> 添加子节点
                </button>
                <button id="editNodeBtn" class="toolbar-btn" disabled>
                    <i class="fas fa-edit"></i> 编辑节点
                </button>
                <button id="deleteNodeBtn" class="toolbar-btn" disabled>
                    <i class="fas fa-trash-alt"></i> 删除节点
                </button>
                <button id="expandAllBtn" class="toolbar-btn">
                    <i class="fas fa-expand"></i> 全部展开
                </button>
                <button id="collapseAllBtn" class="toolbar-btn">
                    <i class="fas fa-compress"></i> 全部折叠
                </button>
            </div>
            
            <div class="tree-container">
                <ul class="tree-menu" id="treeMenu"></ul>
            </div>
            
         
        </div>
       
    </div>

    <script>
        // 树节点类
        class TreeNode {
            constructor(id, name, children = []) {
                this.id = id;
                this.name = name;
                this.children = children;
                this.expanded = false;
                this.loaded = false;
                this.selected = false; // 新增选中状态
            }
        }

        // 树形菜单类
        class TreeMenu {
            constructor(containerId) {
                this.container = document.getElementById(containerId);
                this.treeData = [];
                this.nextId = 1;
                this.selectedNode = null; // 当前选中的节点
                this.loadTreeState();
                this.render();
                this.setupEventListeners();
                this.updateToolbarState();
            }
            
            // 加载树状态
            loadTreeState() {
                const savedTree = localStorage.getItem('treeData');
                if (savedTree) {
                    this.treeData = JSON.parse(savedTree);
                    this.calculateNextId();
                } else {
                    this.initializeDefaultTree();
                }
            }
            
            // 保存树状态
            saveTreeState() {
                localStorage.setItem('treeData', JSON.stringify(this.treeData));
            }
            
            // 计算下一个ID
            calculateNextId() {
                let maxId = 0;
                
                const findMaxId = (nodes) => {
                    nodes.forEach(node => {
                        if (node.id > maxId) maxId = node.id;
                        if (node.children) findMaxId(node.children);
                    });
                };
                
                findMaxId(this.treeData);
                this.nextId = maxId + 1;
            }
            
            // 初始化默认树
            initializeDefaultTree() {
                this.treeData = [
                    new TreeNode(this.nextId++, '项目文档', [
                        new TreeNode(this.nextId++, '需求文档'),
                        new TreeNode(this.nextId++, '设计文档', [
                            new TreeNode(this.nextId++, 'UI设计'),
                            new TreeNode(this.nextId++, '架构设计')
                        ])
                    ]),
                    new TreeNode(this.nextId++, '开发计划', [
                        new TreeNode(this.nextId++, '前端开发'),
                        new TreeNode(this.nextId++, '后端开发'),
                        new TreeNode(this.nextId++, '测试计划')
                    ]),
                    new TreeNode(this.nextId++, '会议记录')
                ];
            }
            
            // 渲染树
            render() {
                this.container.innerHTML = '';
                this.treeData.forEach(node => this.renderNode(node, this.container));
                this.updateSelectedNodeInfo();
            }
            
            // 渲染节点
            renderNode(node, parentElement) {
                const li = document.createElement('li');
                li.className = 'tree-node';
                li.dataset.id = node.id;
                
                const nodeContent = document.createElement('div');
                nodeContent.className = `node-content ${node.selected ? 'selected' : ''}`;
                
                const toggleIcon = document.createElement('div');
                toggleIcon.className = 'toggle-icon';
                
                if (node.children.length > 0 || !node.loaded) {
                    toggleIcon.innerHTML = node.expanded ? 
                        '<i class="iconfont-arrow">&#xe730;</i>' : 
                        '<i class="iconfont-arrow">&#xe509;</i>';
                } 
                // 添加文件夹图标
                const folderIcon = document.createElement('div');
                folderIcon.className = 'folder-icon';
                folderIcon.innerHTML = node.expanded && (node.children.length > 0 || !node.loaded) ? 
                    '<i class="iconfont-folder">&#xe6a3;</i>' : 
                    '<i class="iconfont-folder">&#xe80c;</i>';
                
                const label = document.createElement('div');
                label.className = 'node-label';
                label.textContent = node.name;
                
                nodeContent.appendChild(toggleIcon);
                nodeContent.appendChild(folderIcon);
                nodeContent.appendChild(label);
                
                li.appendChild(nodeContent);
                
                const childrenContainer = document.createElement('ul');
                childrenContainer.className = 'children';
                
                if (node.expanded) {
                    childrenContainer.style.display = 'block';
                    
                    if (node.children.length > 0) {
                        node.children.forEach(child => this.renderNode(child, childrenContainer));
                    } else if (!node.loaded) {
                        // 显示加载中
                        const loading = document.createElement('div');
                        loading.className = 'loading';
                        loading.innerHTML = '<div class="spinner"></div> 加载中...';
                        childrenContainer.appendChild(loading);
                        
                        // 模拟异步加载
                        this.loadChildren(node, childrenContainer);
                    }
                }
                
                li.appendChild(childrenContainer);
                parentElement.appendChild(li);
                
                // 设置展开状态类
                if (node.expanded) {
                    li.classList.add('expanded');
                }
            }
            
            // 模拟异步加载子节点
            loadChildren(node, container) {
                // 模拟API请求延迟
                setTimeout(() => {
                    // 模拟API数据
                    const newChildren = [
                        new TreeNode(this.nextId++, `子节点 ${node.id}-1`),
                        new TreeNode(this.nextId++, `子节点 ${node.id}-2`),
                        new TreeNode(this.nextId++, `子节点 ${node.id}-3`, [])
                    ];
                    
                    node.children = newChildren;
                    node.loaded = true;
                    
                    // 移除加载指示器
                    container.innerHTML = '';
                    
                    // 渲染新节点
                    newChildren.forEach(child => this.renderNode(child, container));
                    
                    this.saveTreeState();
                }, 1000);
            }
            
            // 添加节点
            addNode(parentId, name) {
                const newNode = new TreeNode(this.nextId++, name);
                
                if (!parentId) {
                    // 添加根节点
                    this.treeData.push(newNode);
                } else {
                    // 查找父节点
                    const parentNode = this.findNode(parentId, this.treeData);
                    if (parentNode) {
                        parentNode.children.push(newNode);
                        // 自动展开父节点
                        if (!parentNode.expanded) {
                            parentNode.expanded = true;
                        }
                    }
                }
                
                this.saveTreeState();
                this.render();
            }
            
            // 编辑节点
            editNode(nodeId, newName) {
                const node = this.findNode(nodeId, this.treeData);
                if (node) {
                    node.name = newName;
                    this.saveTreeState();
                    this.render();
                }
            }
            
            // 删除节点
            deleteNode(nodeId) {
                const deleteRecursive = (nodes, id) => {
                    for (let i = 0; i < nodes.length; i++) {
                        if (nodes[i].id === id) {
                            // 如果删除的是选中的节点，清除选中状态
                            if (this.selectedNode && this.selectedNode.id === id) {
                                this.selectedNode = null;
                                this.updateToolbarState();
                            }
                            nodes.splice(i, 1);
                            return true;
                        }
                        
                        if (nodes[i].children && nodes[i].children.length > 0) {
                            if (deleteRecursive(nodes[i].children, id)) {
                                return true;
                            }
                        }
                    }
                    return false;
                };
                
                deleteRecursive(this.treeData, nodeId);
                this.saveTreeState();
                this.render();
            }
            
            // 查找节点
            findNode(id, nodes) {
                for (const node of nodes) {
                    if (node.id === id) {
                        return node;
                    }
                    
                    if (node.children && node.children.length > 0) {
                        const found = this.findNode(id, node.children);
                        if (found) return found;
                    }
                }
                return null;
            }
            
            // 切换节点展开状态
            toggleNode(nodeId) {
                const node = this.findNode(nodeId, this.treeData);
                if (node) {
                    node.expanded = !node.expanded;
                    this.saveTreeState();
                    this.render();
                }
            }
            
            // 展开所有节点
            expandAll() {
                const expand = (nodes) => {
                    nodes.forEach(node => {
                        node.expanded = true;
                        if (node.children && node.children.length > 0) {
                            expand(node.children);
                        }
                    });
                };
                
                expand(this.treeData);
                this.saveTreeState();
                this.render();
            }
            
            // 折叠所有节点
            collapseAll() {
                const collapse = (nodes) => {
                    nodes.forEach(node => {
                        node.expanded = false;
                        if (node.children && node.children.length > 0) {
                            collapse(node.children);
                        }
                    });
                };
                
                collapse(this.treeData);
                this.saveTreeState();
                this.render();
            }
            
            // 选中节点
            selectNode(nodeId) {
                // 清除之前选中的节点
                this.clearSelection(this.treeData);
                
                // 设置新选中的节点
                const node = this.findNode(nodeId, this.treeData);
                if (node) {
                    node.selected = true;
                    this.selectedNode = node;
                    this.updateToolbarState();
                    this.render();
                }
            }
            
            // 清除所有节点的选中状态
            clearSelection(nodes) {
                nodes.forEach(node => {
                    node.selected = false;
                    if (node.children && node.children.length > 0) {
                        this.clearSelection(node.children);
                    }
                });
            }
            
            // 更新选中节点信息
            updateSelectedNodeInfo() {
				this.selectedNode
               
            }
            
            // 更新工具栏状态
            updateToolbarState() {
                const hasSelection = this.selectedNode !== null;
                document.getElementById('addChildBtn').disabled = !hasSelection;
                document.getElementById('editNodeBtn').disabled = !hasSelection;
                document.getElementById('deleteNodeBtn').disabled = !hasSelection;
            }
            
          
       
            // 获取所有节点（扁平化）
            getAllNodes() {
                const nodes = [];
                
                const traverse = (nodeList) => {
                    nodeList.forEach(node => {
                        nodes.push(node);
                        if (node.children && node.children.length > 0) {
                            traverse(node.children);
                        }
                    });
                };
                
                traverse(this.treeData);
                return nodes;
            }
            
            // 设置事件监听器
            setupEventListeners() {
                // 节点点击事件
                this.container.addEventListener('click', (e) => {
                    const target = e.target;
                    const nodeElement = target.closest('.tree-node');
                    
                    if (!nodeElement) return;
                    
                    const nodeId = parseInt(nodeElement.dataset.id);
                    
                    // 切换图标点击
                    if (target.closest('.toggle-icon')) {
                        this.toggleNode(nodeId);
                        return;
                    }
                    
                    // 节点标签点击 - 选中节点
                    if (target.closest('.node-label') || 
                        target.closest('.node-content') || 
                        target.closest('.folder-icon')) {
                        this.selectNode(nodeId);
                    }
                });
                
                // 添加根节点按钮
                document.getElementById('addRootBtn').addEventListener('click', () => {
                    const name = prompt('请输入根节点名称:', '新节点');
                    if (name) {
                        this.addNode(null, name);
                    }
                });
                
                // 添加子节点按钮
                document.getElementById('addChildBtn').addEventListener('click', () => {
                    if (!this.selectedNode) return;
                    
                    const name = prompt('请输入子节点名称:', '新子节点');
                    if (name) {
                        this.addNode(this.selectedNode.id, name);
                    }
                });
                
                // 编辑节点按钮
                document.getElementById('editNodeBtn').addEventListener('click', () => {
                    if (!this.selectedNode) return;
                    
                    const newName = prompt('编辑节点名称:', this.selectedNode.name);
                    if (newName !== null) {
                        this.editNode(this.selectedNode.id, newName);
                    }
                });
                
                // 删除节点按钮
                document.getElementById('deleteNodeBtn').addEventListener('click', () => {
                    if (!this.selectedNode) return;
                    
                    if (confirm(`确定要删除节点 "${this.selectedNode.name}" 及其所有子节点吗？`)) {
                        this.deleteNode(this.selectedNode.id);
                    }
                });
                
                // 全部展开按钮
                document.getElementById('expandAllBtn').addEventListener('click', () => {
                    this.expandAll();
                });
                
                // 全部折叠按钮
                document.getElementById('collapseAllBtn').addEventListener('click', () => {
                    this.collapseAll();
                });
                
            
            }
        }

        // 初始化树形菜单
        document.addEventListener('DOMContentLoaded', () => {
            const treeMenu = new TreeMenu('treeMenu');
        });
    </script>
</body>
</html>